package com.edu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

    private static final String SECRET_KEY = "YourSecretKeyHere"; // 应该使用安全的方式存储密钥，这里仅为示例

    // 生成JWT
    public static String generateToken(Map<String, ?> claims) {

        Date now = new Date();
        Date expiration = new Date(now.getTime() + 1000 * 100000); // 设置过期时间为一天后

        return JWT.create()
                .withClaim("user", claims)
                .withIssuedAt(now)
                .withExpiresAt(expiration)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    // 解析JWT
    public static Map<String, Object> validateToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
            DecodedJWT jwt = verifier.verify(token);
            Claim user = jwt.getClaim("user");
            System.out.println(user);
            return user.asMap();
        } catch (Exception e) {
            return null;
        }
    }

    // 解析并重置JWT有效期
    public static String refreshAndResetToken(String token) {
        try {
            Map<String, Object> stringObjectMap = validateToken(token);

            // 获取当前时间
            Date now = new Date();
            // 设置新的过期时间
            Date newExpiration = new Date(now.getTime() + 1000 * 5000); // 重新设置过期时间为一天后
            System.out.println(1111);
            // 创建新的JWT
            return JWT.create()
                    .withClaim("user", stringObjectMap)
                    .withIssuedAt(now)
                    .withExpiresAt(newExpiration)
                    .sign(Algorithm.HMAC256(SECRET_KEY));
        } catch (Exception e) {
            System.out.println(2222);
            return null;
        }
    }
}

